<?php

declare(strict_types=1);

namespace Service\WebLiveService;

use MathPHP\Probability\Distribution\Continuous\F;
use Service\BaseService;
use Service\CacheService\CacheProviderService as Cache;
use Service\Code\Normal;
use Service\ExtraService\TaskWorker;

class WebLiveService extends BaseService
{
    /**
     * 获取token地址
     */
    public $token_url = 'http://live.indoorbuy.com/auth/index/method/token';

    /**
     * appid
     */
    public $appid = 'CTyTbSwXNTo1GWWZT3yytS1551087087';

    /**
     * secret
     */
    public $secret = 'fxpwDBjp77hZs9sFJ7B1FR97G1H67wp6';

    /**
     * 获取Token
     * @return array
     */
    public function getToken()
    {
        $cache_key = 'weblive_GetToken';
        $token = Cache::getCacheByKey($cache_key);
        if (!empty($token)) {
            return Normal::returnCode(Normal::SUC,'获取成功',$token);
        }

    
        $parameter = [
            [
                'tag'    => 'web_live_get_token',
                'url'    => $this->token_url,
                'data'   => [
                    'appid'  => $this->appid,
                    'secret' => $this->secret,
                ],
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [],
            ],
        ];
        $resTask   = TaskWorker::instance()->addTask($parameter);
        $resTask   = current($resTask);
        $response  = @json_decode($resTask['response']['result'], true);

        if($response['code'] != Normal::SUC || $response['status'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL,'获取失败');
        }
        Cache::cacheBySetKeyValue($cache_key,$response['data']['token'],3600);
        return Normal::returnCode(Normal::SUC,'获取成功',$response['data']['token']);
    }
}
